package controller;

import java.beans.XMLDecoder;
import java.beans.XMLEncoder;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.Arrays;

import model.State;

public class XMLHandler {

	public static void write(State stateToSave, String filename)
			throws Exception {
		XMLEncoder encoder = new XMLEncoder(new BufferedOutputStream(
				new FileOutputStream(filename)));
		do {
			encoder.writeObject(stateToSave.stateId);
			encoder.writeObject(stateToSave.score);
			encoder.writeObject(Arrays.deepToString(stateToSave.boardState));
		} while ((stateToSave = stateToSave.pState) != null);
		encoder.close();
	}

	public static State read(String filename) throws Exception {
		XMLDecoder decoder = new XMLDecoder(new BufferedInputStream(
				new FileInputStream(filename)));
		ArrayList<State> stateList = new ArrayList<State>();
		Object objId, objScore, objBoard;
		while (((int) (objId = (int) decoder.readObject()) >= -1)
				&& ((int) (objScore = (int) decoder.readObject()) != -999999)
				&& ((int[][]) (objBoard = (int[][]) StringTo2DArray(decoder.readObject().toString())) != null)) {
			stateList.add(new State((int) objId, (int) objScore, (int[][]) objBoard, null));
			if ((int) objId == -1) {
				break;
			}
		}
		decoder.close();
		for (int i = 0; i < stateList.size() - 1; i++) {
			stateList.get(i).pState = stateList.get(i + 1);
		}
		
		return stateList.get(0);
	}
		
	public static int[][] StringTo2DArray(String s) {
		String[] sArr = s.substring(1, s.length() - 2).split("],");
		int[][] intArr = new int[sArr.length][sArr.length];
		int counter = 0;
		for (String row : sArr) {
			String str = row.trim().substring(1);
			String[] numbers = str.split(",");
			for (int i = 0; i < numbers.length; i++) {
				intArr[counter][i] = Integer.parseInt(numbers[i].trim());
			}
			counter++;
		}
		return intArr;
	}
}
